package cn.lyn4ever.cart.service.impl;

import cn.lyn4ever.cart.feign.IGoodsServiceFeign;
import cn.lyn4ever.cart.mapper.CartMapper;
import cn.lyn4ever.cart.service.CartService;
import cn.lyn4ever.common.R;
import cn.lyn4ever.entity.Cart;
import cn.lyn4ever.entity.Store;
import cn.lyn4ever.tool.Tool;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信公众号 “小鱼与Java”
 *
 * @date 2020/4/19
 * @auther Lyn4ever
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;
    @Resource
    private IGoodsServiceFeign iGoodsServiceFeign;

    /**
     * 查询用户的购物车记录
     *
     * @param userid
     * @return
     */
    @Override
    public List<Cart> getList(Integer userid) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("userid",userid);
        wrapper.groupBy("storeid");
        List<Cart> carts = cartMapper.selectList(wrapper);
        List<Cart> lastCart = new ArrayList<>();
        carts.forEach(cart->{
            Integer storeid = cart.getStoreid();
            // 这是为了将对象其他属性置为空，不要引起前端不必要的麻烦
            cart = new Cart();
            lastCart.add(cart);
            // 删除其他于用信息
            R storeById = iGoodsServiceFeign.getStoreById(storeid);
            Store data = (Store) Tool.formatObj(storeById.get("data"), Store.class);
            if(data!=null){
                cart.setStoreName(data.getTitle());
            }

            //查询对应的商品列表
            QueryWrapper<Cart> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("userid",userid);
            wrapper1.eq("storeid", storeid);
            List<Cart> carts1 = cartMapper.selectList(wrapper1);
            cart.setCartDetails(carts1);
        });

        return lastCart;
    }
}
